package com.huatai.datadevelop.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huatai.common.error.exception.ServiceException;
import com.huatai.datadevelop.entity.ApiSuperviseEntity;
import com.huatai.datadevelop.entity.JsonDataEntity;
import com.huatai.datadevelop.mapper.JsonDataMapper;
import com.huatai.datadevelop.utils.PageUtils;
import com.huatai.datadevelop.utils.Query;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class JsonDataService extends ServiceImpl<JsonDataMapper, JsonDataEntity> {

    @Autowired
    private ApiSuperviseService apiSuperviseService;

    /**
     * 获取英文名称是否合规
     *
     * @param interfaceName
     * @return
     */
    public HashMap<String, Object> getTableNameCompliance(String interfaceName) {
        //判断接口名称是否为空
        if (StringUtils.isEmpty(interfaceName)) {
            throw new ServiceException("接口名称为空");
        }
        HashMap<String, Object> hashMap = new HashMap<>(2);
        hashMap.put("success", true);

        //判断是否全是英文
        boolean matches = interfaceName.matches("[a-zA-Z]+");
        if (!matches) {
            hashMap.put("success", false);
            hashMap.put("message", "只能填写英文");
            return hashMap;
        }
        QueryWrapper<JsonDataEntity> qw = new QueryWrapper<>();
        qw.eq("interface_name", interfaceName);
        int count = (int) this.count(qw);
        if (count > 0) {
            hashMap.put("success", false);
            hashMap.put("message", "接口名称重复，请换一个");
            return hashMap;
        }
        hashMap.put("message", "验证通过");
        return hashMap;
    }

    /**
     * Json数据新增或修改
     * @return
     */
    public Boolean getJsonBodyData(JsonDataEntity data){
        Object dataInfo = data.getJsonBody();
        if(dataInfo!=null){
            data.setBodyData(JSON.toJSONString(dataInfo));
        }
        return this.saveOrUpdate(data);
    }

    /**
     * 分页获取数据
     *
     * @param params
     * @return
     */
    public PageUtils queryPage(Map<String, Object> params) {
        String name = (String) params.get("name");
        IPage<JsonDataEntity> page = this.page(
                new Query<JsonDataEntity>().getPage(params),
                new QueryWrapper<JsonDataEntity>().like(StringUtils.isNotBlank(name), "name", name)
        );
        page.getRecords().stream().forEach(p->{
            Object data = null;
            String bodyData = p.getBodyData();
            if(bodyData.startsWith("[")){
                data = JSON.parseArray(bodyData);
            }else {
                data = JSON.parseObject(p.getBodyData());
            }
            p.setJsonBody(data);
        });
        return new PageUtils(page);
    }

    /**
     * 调用数据
     * @return
     */
    public synchronized HashMap<String, Object> asyncRequestApi(JsonDataEntity entity, JSONObject parm) {
        ApiSuperviseEntity apiSuperviseEntity = new ApiSuperviseEntity();
        String type = "静态JSON数据配置";
        try {
            ApiSuperviseEntity interface_name = this.apiSuperviseService.getOne(new QueryWrapper<ApiSuperviseEntity>()
                    .eq("interface_name", entity.getInterfaceName())
                    .eq("type", type));
            if (interface_name != null) {
                apiSuperviseEntity = interface_name;
            }
        } catch (Exception ex) {
        }
        apiSuperviseEntity.setType(type);
        apiSuperviseEntity.setInterfaceName(entity.getInterfaceName());
        apiSuperviseEntity.setName(entity.getName());
        apiSuperviseEntity.setUrl("/ht-datadevelop/api/execute/asyncStaticJsonRequestApi/" + entity.getInterfaceName());
        apiSuperviseEntity.setSuperviseTime(new Date());
        HashMap<String, Object> retDa = new HashMap<>();
        JSONObject object = JSON.parseObject(entity.getBodyData());
        //保存数据库中时候必须有一个data
        Object data = object.get("data");
        //存在根据参数取数据
        if(parm!=null && parm.size()>0){
            //查询的键值
            String key = parm.getString("key");
            //查询的value
            String value = parm.getString("value");
            List<JSONObject> dataInfoList = new ArrayList<>();
            if(data instanceof ArrayList || data instanceof JSONArray){
                List<JSONObject> jsonObjects = JSON.parseArray(JSON.toJSONString(data), JSONObject.class);
                jsonObjects.stream().forEach(dataInfo->{
                    if(dataInfo!=null){
                        String keyValue = dataInfo.getString(key);
                        if(keyValue.contains(value)){
                            dataInfoList.add(dataInfo);
                        }
                    }
                });
            }
            else {
                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(data));
                String keyValue = jsonObject.getString(key);
                if(keyValue.equalsIgnoreCase(value)){
                    dataInfoList.add(jsonObject);
                }
            }
            retDa.put("dataInfo",dataInfoList);
        }
        else {
            retDa.put("dataInfo",data);
        }
        return retDa;
    }

    /**
     * 获取数据
     * @param entity
     * @return
     */
    public synchronized Object asyncStaticJsonApi(JsonDataEntity entity) {
        Object objectData = null;
        ApiSuperviseEntity apiSuperviseEntity = new ApiSuperviseEntity();
        String type = "静态JSON数据配置";
        try {
            ApiSuperviseEntity interface_name = this.apiSuperviseService.getOne(new QueryWrapper<ApiSuperviseEntity>()
                    .eq("interface_name", entity.getInterfaceName())
                    .eq("type", type));
            if (interface_name != null) {
                apiSuperviseEntity = interface_name;
            }
        } catch (Exception ex) {
        }
        apiSuperviseEntity.setType(type);
        apiSuperviseEntity.setInterfaceName(entity.getInterfaceName());
        apiSuperviseEntity.setName(entity.getName());
        apiSuperviseEntity.setUrl("/ht-datadevelop/api/execute/asyncStaticJsonApi/" + entity.getInterfaceName());
        apiSuperviseEntity.setSuperviseTime(new Date());
        String bodyData = entity.getBodyData();
        if(bodyData.startsWith("[")){
            objectData = JSON.parseArray(entity.getBodyData());
        }else {
            objectData = JSON.parseObject(entity.getBodyData());
        }
        return objectData;
    }
}
